package com.example.demo.controller;

import com.example.demo.common.handler.CustomException;
import com.example.demo.entity.dto.TaskDTO;
import com.example.demo.service.task.TimedTaskService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;

/**
 * @author: ak
 * @date: 2020/5/5 21:21
 * @description:
 */
@RestController
class TaskController {
    @Autowired
    TimedTaskService timedTaskService;

    /**
     * 发布任务
     * 传入参数endTime，taskKey，data
     */
    @GetMapping("publishTask")
    public Object publishTask(@Valid TaskDTO taskDTO, BindingResult result) throws CustomException {
        HashMap<Object, Object> map = new HashMap<>(2);
        if (result.hasErrors()){
            String message = result.getFieldError().getDefaultMessage();
            map.put("msg",message);
            map.put("status",500);
            return map;
        }
        checkTime(taskDTO);
        return timedTaskService.publishTask(taskDTO);
    }

    /**
     * 获取还未截至的任务
     *
     * @param taskKey 任务唯一标识key
     */
    @GetMapping("getTask")
    public Object getTask(String taskKey) throws SchedulerException {
        HashMap<Object, Object> map = new HashMap<>(16);
        if (taskKey == null) {
            map.put("msg", "请输入任务指定表示符key");
            map.put("status", 400);
            return map;
        }
        return timedTaskService.getTask(taskKey);
    }

    /**
     * 修改还未截至的任务
     * 传入参数changeTime
     */
    @GetMapping("changeTaskTime")
    public Object changeTaskTime(TaskDTO taskDTO) throws SchedulerException {
        HashMap<Object, Object> map = new HashMap<>(2);
        if (taskDTO.getTaskKey()==null){
            map.put("msg","taskKey不能为空");
            map.put("status",500);
            return map;
        }
        checkTime(taskDTO);
        //如果需要更新数据，则传入新的json字符串，否则传空值
        return timedTaskService.changeTaskTime(taskDTO);
    }

    /**
     * 如果传入的时间戳只精确到秒，则转换成毫秒
     */
    public void checkTime(TaskDTO taskDTO) {
        if (taskDTO.getEndTime() != null && taskDTO.getEndTime().toString().length() == 10) {
            taskDTO.setEndTime(taskDTO.getEndTime() * 1000);
        }
        if (taskDTO.getChangeTime() != null && taskDTO.getChangeTime().toString().length() == 10) {
            taskDTO.setChangeTime(taskDTO.getChangeTime() * 1000);
        }
    }
}
